<template>
	<uni-forms ref="form" :modelValue="form" :rules="rules" label-position="top">
		<!-- 工单基本信息 -->
		<view class="header-section">
			<uni-card class="header-card">
				<template v-slot:title>
					<uni-title type="h3" title="工单基本信息" color="#027fff" />
					<view class="mine-actions grid col-2">
						<view class="text">
							工单编号:{{order_info.orderNo}}
						</view>
						<view class="text">
							报修时间:{{order_info.reportedTime}}
						</view>
					</view>
					<view class="mine-actions grid col-2">
						<view class="text">
							设备编号:{{facility_info.elevatorCode}}
						</view>
						<view class="text">
							设备类型:{{resolveElevatorType(facility_info.elevatorType)}}
						</view>
					</view>
					<view class="mine-actions grid col-2">
						<view class="text">
							设备品牌:{{facility_info.brand}}
						</view>
						<view class="text">
							设备型号:{{facility_info.model}}
						</view>
					</view>
					<view class="mine-actions grid col-2">
						<view class="text">
							报修人:{{order_info.reportedBy}}
						</view>
						<view class="text">
							报修内容:{{order_info.faultDescription}}
						</view>

					</view>
				</template>
			</uni-card>
		</view>
		<!-- 检查项目 -->
		<view class="inspection-item">
			<uni-card class="inspection-card">
				<template v-slot:title>
					<uni-title type="h3" title="检查项目" color="#027fff" />
				</template>
				<uni-forms-item label="1.门机开关门信号输入是否正常" label-width="400" name="isDrive" required>
					<uni-data-checkbox mode="tag" v-model="form.isDrive" :localdata="check_status_1" />
				</uni-forms-item>
				<uni-forms-item label="2.门导轨有无形变 " label-width="400" name="isGuise" required>
					<uni-data-checkbox mode="tag" v-model="form.isGuise" :localdata="check_status_2" />
				</uni-forms-item>
				<uni-forms-item label="3.地坎有无异物卡阻" label-width="400" name="isElectric" required>
					<uni-data-checkbox mode="tag" v-model="form.isElectric" :localdata="check_status_2" />
				</uni-forms-item>
				<uni-forms-item label="4.门联锁触点是否同步闭合" label-width="400" name="isIntact" required>
					<uni-data-checkbox mode="tag" v-model="form.isIntact" :localdata="check_status_1" />
				</uni-forms-item>
				<uni-forms-item label="5.开关门是否到位" label-width="400" name="isNoise" required>
					<uni-data-checkbox mode="tag" v-model="form.isNoise" :localdata="check_status_1" />
				</uni-forms-item>
			</uni-card>
		</view>
		<!-- 现场照片 -->
		<view class="site-photos">
			<uni-card class="site-photos-card">
				<uni-forms-item name="sitePhotos" required>
					<template v-slot:label>
						<uni-title type="h3" title="现场照片" color="#027fff" />
					</template>
					<uni-file-picker v-model="form.sitePhotos" limit="9" title="最多选择9张图片" :auto-upload="false"
						@select="siteFileUpload" />
				</uni-forms-item>
			</uni-card>
		</view>
		<!-- 维修详细 -->
		<view class="site-photos">
			<uni-card class="site-photos-card">
				<template v-slot:title>
					<uni-title type="h3" title="维修详细" color="#027fff" />
				</template>
				<uni-forms-item name="faultAnalysis" required>
					<template v-slot:label>
						<uni-title type="h4" title="故障描述" color="#000000" />
					</template>
					<textarea v-model="form.faultAnalysis" placeholder="请详细描述故障情况..." />
				</uni-forms-item>
				<uni-forms-item name="repairMethod" required>
					<template v-slot:label>
						<uni-title type="h4" title="处理方法" color="#000000" />
					</template>
					<textarea v-model="form.repairMethod" placeholder="请详细描述处理方法..." />
				</uni-forms-item>
				<uni-forms-item class="change-part" name="sitePhotos" required>
					<template v-slot:label>
						<view style="display: flex;">
							<uni-title type="h4" title="更换零件" color="#000000" />
							<view style="padding-right: 20px;">
								<button type="primary" size="mini" @click="addRow">加一行</button>
							</view>
							<scan-QC-codes />
						</view>
					</template>
					<view class="table-container">
						<uni-table class="uni-table">
							<uni-tr>
								<uni-th>序号</uni-th>
								<uni-th>零件编码</uni-th>
								<uni-th>操作</uni-th>
							</uni-tr>
							<uni-tr v-for="(item,index) in form.partsReplaced" :key="index">
								<uni-td>{{index + 1}}</uni-td>
								<uni-td>
									<view class="select-wrapper">
										<uni-data-select v-model="item.materialCode" placeholder="请选择材料"
											:localdata="materialList" clear />
									</view>
								</uni-td>
							</uni-tr>
						</uni-table>
					</view>
				</uni-forms-item>
				<uni-forms-item name="completePhotos" required>
					<template v-slot:label>
						<uni-title type="h4" title="完成照片" color="#000000" />
					</template>
					<view>
						<uni-file-picker v-model="form.completePhotos" limit="9" title="最多选择9张图片" :auto-upload="false"
							@select="completeFileUpload" />
					</view>
				</uni-forms-item>
			</uni-card>
		</view>
		<!-- 处理人签名/完成时间-->
		<view class="bottom-finish">
			<uni-card class="site-photos-card">
				<uni-forms-item class="dispose-item" name="signatureUrl">
					<template v-slot:label>
						<uni-title type="h4" title="处理人签名" color="#000000" />
					</template>
					<jp-signature-popup v-model="form.signatureUrl" label="" required=true @input="handleSignature" />
				</uni-forms-item>
			</uni-card>
		</view>
		<view class="bottom-item">
			<view class="button-select">
				<button type="primary" @click="handleFrom">提交工单</button>
			</view>
		</view>

	</uni-forms>
</template>

<script>
	import {
		getToken
	} from '@/utils/auth'
	import {
		getRepairReportByOrderId,
		addRepairReport,
		updateRepairReport
	} from "@/api/repairManage/repairer.js"
	import {
		getOrder
	} from "@/api/repairManage/order.js"
	import {
		getElevatorManagement
	} from "@/api/deviceManagement/elevatorManagement.js"
	import {
		allMaterialInfo
	} from "@/api/repairManage/materialInfo.js"
	export default {
		onLoad(options) {
			console.log("=========维修报告=========");
			console.log(options);
		},
		data() {
			return {
				// 工单基本信息
				order_info: {},
				// 设备信息
				facility_info: {},
				// 维修报告信息
				repairReport: undefined,
				// 材料列表
				materialList: [],
				// 提交表单
				form: {
					// 设备是否完好
					isGuise: "",
					// 电气是否正常
					isElectric: "",
					// 传动是否正常
					isDrive: "",
					// 防护是否正常
					isIntact: "",
					// 运动是否有噪音
					isNoise: "",
					// 处理方法
					repairMethod: "",
					// 签名
					signatureUrl: "",
					// 签名文件
					signatureUrlFile: "",
					// 完成时间
					finish_time: "",
					// 故障描述
					faultAnalysis: "",
					// 故障部位
					faultLocation: "",
					// 现场照片
					sitePhotos: [],
					// 处理照片
					completePhotos: [],
					// 是否当场修复
					siteRepair: '',
					// 更换零件
					partsReplaced: []
				},
				// 初始化电梯类型
				elevatorTypeList: [],
				// 检查状态
				check_status_1: [{
						"text": "是",
						"value": "1",
					},
					{
						"text": "否",
						"value": "2",
					}, {
						"text": "跳过",
						"value": "0",
					}
				],
				// 是否有无
				check_status_2: [{
						"text": "有",
						"value": "1",
					},
					{
						"text": "无",
						"value": "2",
					}, {
						"text": "跳过",
						"value": "0",
					}
				],
				// 表单校验
				rules: {
					isGuise: {
						rules: [{
							required: true,
							errorMessage: '门导轨有无形变不能为空'
						}]
					},
					isElectric: {
						rules: [{
							required: true,
							errorMessage: '坎有无异物卡阻不能为空'
						}]
					},
					isDrive: {
						rules: [{
							required: true,
							errorMessage: '门机开关门信号输入是否正常不能为空'
						}]
					},
					isIntact: {
						rules: [{
							required: true,
							errorMessage: '门联锁触点是否同步闭合不能为空'
						}]
					},
					isNoise: {
						rules: [{
							required: true,
							errorMessage: '开关门是否到位不能为空'
						}]
					},
					faultAnalysis: {
						rules: [{
							required: true,
							errorMessage: '故障描述不能为空'
						}]
					},
					repairMethod: {
						rules: [{
							required: true,
							errorMessage: '维修方法不能为空'
						}]
					},
					faultLocation: {
						rules: [{
							required: true,
							errorMessage: '故障部位不能为空'
						}]
					},
					sitePhotos: {
						rules: [{
							type: 'array',
							required: true,
							errorMessage: '现场照片不能为空'
						}]
					},
					completePhotos: {
						rules: [{
							type: 'array',
							required: true,
							errorMessage: '完成照片不能为空'
						}]
					},
					siteRepair: {
						rules: [{
							required: true,
							errorMessage: '是否能当场修复不能为空'
						}]
					},
					signatureUrl: {
						rules: [{
							required: true,
							errorMessage: '处理人签名不能为空'
						}]
					},
				}
			};
		},
		onLoad(options) {
			console.log("========= 现场诊断 =========");
			this.orderId = options.orderId

			this.getOrderDate();
			this.getOrderInfo();
		},
		created() {
			this.getmaterialList();
			this.getelevatorTypeList();
		},
		methods: {
			// 获取 订单信息
			getOrderInfo() {
				getRepairReportByOrderId(this.orderId).then(res => {
					if (res != undefined && res != null) {
						this.repairReport = res.data
						this.form.faultAnalysis = res.data.faultAnalysis
						this.form.faultLocation = res.data.faultLocation
						this.form.sitePhotos = res.data.sitePhotos.split(",").map(item => this.createFileObject(
							item))
						this.form.siteRepair = res.data.siteRepair
						this.form.repairMethod = res.data.repairMethod
						this.form.isDrive = res.data.isDrive
						this.form.isElectric = res.data.isElectric
						this.form.isGuise = res.data.isGuise
						this.form.isIntact = res.data.isIntact
						this.form.isNoise = res.data.isNoise
						this.form.completePhotos = res.data.completePhotos.split(",").map(item => this
							.createFileObject(item))
						const url = res.data.signatureUrl
						this.form.signatureUrl = url.startsWith('http') ? url : getApp().globalData.config
							.baseUrl + url
						this.form.signatureUrlFile = url
						this.form.partsReplaced = res.data.partsReplaced.split(",").map(item => this.createObject(
							item))
					}
				}).then(() => {
					if (this.repairReport == undefined) {
						getOrder(this.orderId).then(res => {
							this.form.orderInfo = res.data
							this.form.faultAnalysis = res.data.faultDescription
						})
					}
				})
			},
			// 初始化目录
			createFileObject(url) {
				if (typeof url !== 'string' || url.trim() === '') {
					return {
						'url': '',
						'fileName': ''
					}
				}
				const fullUrl = url.startsWith('http') ? url : getApp().globalData.config.baseUrl + url;
				return {
					"url": fullUrl,
					"fileName": url
				};
			},
			// 初始化订单
			createObject(materialCode) {
				return {
					'materialCode': materialCode
				}
			},
			//订单基础信息
			getOrderDate() {
				getOrder(this.orderId).then(res => {
					this.order_info = res.data
				}).then(() => {
					this.getFacility();
				})
			},
			// 设备基础信息
			getFacility() {
				const _this = this
				getElevatorManagement(this.order_info.elevatorId).then(res => {
					this.facility_info = res.data
				})
			},
			// 获取电梯材料
			getmaterialList() {
				const list = []
				allMaterialInfo({}).then(res => {
					res.rows.forEach(item => {
						list.push({
							"value": item.materialCode,
							"text": item.materialName
						})
					})
				})
				this.materialList = list
			},
			// 获取电梯设备类型
			async getelevatorTypeList() {
				this.getDicts("elevator_type").then(res => {
					this.elevatorTypeList = res.data;
				})
			},
			// 加一行
			addRow() {
				this.form.partsReplaced.push({
					materialCode: '',
				});
			},
			// 解析电梯类型
			resolveElevatorType(elevatorType) {
				return this.elevatorTypeList.find(item => item.dictValue=== "1")?.dictLabel;
			},

			// 现场照片文件上传
			siteFileUpload(e) {
				const tempFilePaths = e.tempFilePaths;
				uni.uploadFile({
					url: getApp().globalData.config.baseUrl + '/common/upload',
					//你的上传文件的接口地址：若依的一般就是这个
					filePath: tempFilePaths[0],
					name: 'file',
					header: {
						Authorization: "Bearer " + getToken()
					},
					success: (res) => {
						// console.log(uploadFileRes.data);
						const imgUrls = JSON.parse(res.data).fileName;
						console.log(imgUrls);
						this.form.sitePhotos.push(this.createFileObject(imgUrls))
						//this.selectedImg是我定义的获取文件的属性，每个用逗号隔开。
						console.log(this.form.sitePhotos);
					}
				});
			},
			// 完成照片文件上传
			completeFileUpload(e) {
				const tempFilePaths = e.tempFilePaths;
				uni.uploadFile({
					url: getApp().globalData.config.baseUrl + '/common/upload',
					//你的上传文件的接口地址：若依的一般就是这个
					filePath: tempFilePaths[0],
					name: 'file',
					header: {
						Authorization: "Bearer " + getToken()
					},
					success: (res) => {
						const imgUrls = JSON.parse(res.data).fileName;
						this.form.completePhotos.push(this.createFileObject(imgUrls))
						//this.selectedImg是我定义的获取文件的属性，每个用逗号隔开。
						console.log(this.form.completePhotos);
					}
				});
			},
			// 处理签名上传
			handleSignature(base64) {
				console.log(base64);
				if (base64 != undefined && base64 != "") {
					let tempPath = ''; // 用 let，不用 const，这样可以重新赋值
					if (/^data:image\/\w+;base64,/.test(base64)) {
						tempPath = this.base64ToTempFilePath(base64);
					} else {
						// 已经是本地路径（iOS _doc/ 或者其他）
						console.log(base64);
						tempPath = plus.io.convertLocalFileSystemURL(base64);
						console.log(tempPath);
					}
					uni.uploadFile({
						url: getApp().globalData.config.baseUrl + '/common/upload',
						filePath: tempPath,
						name: 'file',
						header: {
							Authorization: "Bearer " + getToken()
						},
						success: (res) => {
							const fileData = JSON.parse(res.data);
							console.log(fileData);
							const fileUrl = fileData.url;
							const fileName = fileData.fileName;
							this.form.signatureUrlFile = fileName; // 存文件名到表单
							this.form.signatureUrl = fileUrl; // 存文件名到表单
						}
					});
				}
			},
			// Base64 转临时路径
			base64ToTempFilePath(base64Data) {
				// 去掉 data:image/png;base64, 头部
				const base64 = base64Data.replace(/^data:image\/\w+;base64,/, "");
				const fileName = `signature_${Date.now()}.png`;

				// #ifdef MP-WEIXIN
				const filePath = `${wx.env.USER_DATA_PATH}/${fileName}`;
				const buffer = uni.base64ToArrayBuffer(base64);
				wx.getFileSystemManager().writeFileSync(filePath, buffer, 'binary');
				return filePath;
				// #endif

				// #ifdef APP-PLUS
				const bitmap = new plus.nativeObj.Bitmap("bitmap");
				bitmap.loadBase64Data(base64Data, () => {
					const filePath = `_doc/${fileName}`;
					bitmap.save(filePath, {
						overwrite: true
					}, () => {
						bitmap.clear();
					});
				});
				return plus.io.convertLocalFileSystemURL(`_doc/${fileName}`);
				// #endif

				// #ifdef H5
				const byteString = atob(base64);
				const arrayBuffer = new ArrayBuffer(byteString.length);
				const intArray = new Uint8Array(arrayBuffer);
				for (let i = 0; i < byteString.length; i++) {
					intArray[i] = byteString.charCodeAt(i);
				}
				const blob = new Blob([intArray], {
					type: 'image/png'
				});
				return URL.createObjectURL(blob);
				// #endif
			},
			// 提交表单
			handleFrom() {
				console.log("========= 订单详情 =========");
				this.$refs.form.validate().then(res => {
					console.log("========= 判断报告类型 =========");
					if (this.repairReport == undefined) {
						console.log("========= 创建维修报告 =========");
						const sitePhotos = this.form.sitePhotos.flatMap(item => item.fileName)
						const completePhotos = this.form.completePhotos.flatMap(item => item.fileName)
						const partsReplaced = this.form.partsReplaced.flatMap(item => item.materialCode)
						const addDate = {
							"orderId": this.orderId,
							"isGuise": this.form.isGuise,
							"isElectric": this.form.isElectric,
							"isDrive": this.form.isDrive,
							"isIntact": this.form.isIntact,
							"isNoise": this.form.isNoise,
							"repairMethod": this.form.repairMethod,
							"sitePhotos": sitePhotos.join(","),
							"completePhotos": completePhotos.join(","),
							"partsReplaced": partsReplaced.join(","),
							"signatureUrl": this.form.signatureUrlFile,
							"faultAnalysis": this.form.faultAnalysis,
							"faultLocation": this.form.faultLocation,
							"siteRepair": this.form.siteRepair,
						}
						addRepairReport(addDate).then(res => {
							this.$tab.navigateTo("/pages/indent/info?orderId=" + this.orderId)
						})
					} else if (this.repairReport != undefined && this.repairReport.reportId != undefined) {
						console.log("========= 更新维修报告 =========");

						const sitePhotos = this.form.sitePhotos.flatMap(item => item.fileName)
						this.repairReport.sitePhotos = sitePhotos.join(",")
						const completePhotos = this.form.completePhotos.flatMap(item => item.fileName)
						this.repairReport.completePhotos = completePhotos.join(",")
						const partsReplaced = this.form.partsReplaced.flatMap(item => item.materialCode)
						this.repairReport.partsReplaced = partsReplaced.join(",")
						this.repairReport.isGuise = this.form.isGuise
						this.repairReport.isElectric = this.form.isElectric
						this.repairReport.isDrive = this.form.isDrive
						this.repairReport.isIntact = this.form.isIntact
						this.repairReport.isNoise = this.form.isNoise
						this.repairReport.repairMethod = this.form.repairMethod
						this.repairReport.signatureUrl = this.form.signatureUrlFile
						this.repairReport.faultAnalysis = this.form.faultAnalysis
						this.repairReport.faultLocation = this.form.faultLocation
						this.repairReport.siteRepair = this.form.siteRepair
						updateRepairReport(this.repairReport).then(res => {
							this.$tab.navigateTo("/pages/indent/info?orderId=" + this.orderId)
						})
					} else {
						this.$modal.msgError("操作失败")
						this.$tab.navigateBack()
					}

				}).catch(err => {
					this.$modal.msgError(err[0].errorMessage)
				})
			},
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: #FFFFFF;
		width: 100%;
		height: 100%;
	}

	.header-section {
		.header-card {
			.text {
				overflow: hidden;
				white-space: nowrap;
				text-overflow: ellipsis;
				-o-text-overflow: ellipsis;
				padding-left: 1%;
				font-family: 仿宋体;
				font-size: 12.75px;
				font-weight: normal;
				line-height: 17.5px;
				letter-spacing: 0px;
				font-feature-settings: "kern" on;
				color: #4B5563;
			}

			.site-photos-table {
				width: 100%;
			}
		}
	}

	.inspection-item {}

	.site-photos {
		position: relative;

		.site-photos-card {
			position: relative;

			// 更换零件
			.change-part {}

			.table-container {
				width: 100%;
				box-sizing: border-box;
			}

			/* 可选：为 uni-table 添加样式以确保其撑满容器 */
			uni-table {
				width: 100% !important;

				.select-wrapper {
					position: relative;
					z-index: 999;
				}

				::v-deep .uni-data-select__selector {
					z-index: 9999 !important;
				}
			}
		}
	}

	.bottom-finish {
		.dispose-item {}

		.finish-item {

			.finish-time {
				width: 80%;
			}
		}
	}


	.bottom-item {
		padding-bottom: 5%;

		.button-select {
			margin: auto;
			width: 90%;
		}
	}
</style>